package org.viva.secu;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.viva.entity.secu.Role;
import org.viva.entity.secu.User;
import org.viva.service.secu.UserService;

public class Realm extends AuthorizingRealm {

	@Resource
	private UserService userService;

	/**
	 * 授权信息
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.fromRealm(getName()).iterator().next();
		if (username != null) {
			User user = userService.getUserByName(username);
			if (user != null && user.getRoles() != null) {
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				for (Role role : user.getRoles()) {
					info.addRole(role.getName());
					info.addStringPermissions(role.getPermissionsAsString());
				}
				return info;
			}
		}
		return null;
	}

	/**
	 * 认证信息
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		if (userName == null || "".equals(userName)) throw new UnknownAccountException("没有找到该账号");
		User user = userService.getUserByName(userName);
		if (user == null) throw new UnknownAccountException("没有找到该账号");
		if (!user.getPassword().equals(new String(token.getPassword()))) throw new UnknownAccountException("没有找到该账号");
		Security.login(user);
		return new SimpleAuthenticationInfo(user.getCode(), user.getPassword(), getName());
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
